import re
import os
import json
import time

##########################################################
# scan files in a give directory with given pattern
# Output is a list of files with ascended order.
def scan_dir(dirname,ptn):
    filelist = []
    pattern = re.compile(ptn)

    for root, dirs, files in os.walk(dirname):
        for fname in files:
            if pattern.match(fname):
                filename = root+"/"+fname
                filelist.append(filename)

    filelist = sorted(filelist)
    return filelist

################ JSON FILE/DATA OPERATION #################
# load a json file into data structure.
def load_file(fn):
    if not os.path.exists(fn):
        return None
    f = open(fn,'r')
    data = json.load(f)
    f.close()
    return data

def save_file(fn,data):
    f = open(fn,'w')
    json.dump(data,f)
    f.close()

def str2data(s):
    return json.loads(s.replace('/n',''))

def append_tofile(fn,data):
    d = json.dumps(data)
    f = open(fn,'a')
    f.write(d+'\n')
    f.close()

################## #######################
def isnan(x):
    return str(x) == str(1e400*0)

def time2str(t):
    st = time.strftime('%m/%d %H:%M:%S', time.localtime(t))
    return st

def time2hms(t):
    
    st = time.strftime('%H:%M:%S', time.localtime(t))
    return st
 
########## dictionary ##################
def list_allkeys(list_of_dict):
    keys =[]
    for dic in list_of_dict:
        keys = set(keys)|set(dic.keys())
    return keys   

def dict_allkeys(dict_of_dict):
    keys =[]
    for k,dic in dict_of_dict.items():
        keys = set(keys)|set(dic.keys())
    return keys
############# WIFI ##################
def wifi_dist(w1, w2):
    k1 = w1.keys()
    k2 = w2.keys()
    weights = {}

    k1 = set(k1)
    k2 = set(k2)
    union = k1 | k2
    inters = k1 & k2
    #print union
    #print inters
    for k in union:
        total_v = 0
        total_cnt = 0
        if k in k1:
            total_v += w1[k] #+ 100
            total_cnt += 1
        if k in k2:
            total_v += w2[k] #+ 100
            total_cnt += 1
        
        weights[k] = 1 #total_v / total_cnt
        

    weight_union = 0
    weight_inters = 0
    for k in union:

        if k not in w1:
            w1k = -110
        else:
            w1k = w1[k]
        if k not in w2:
            w2k = -110
        else:
            w2k = w2[k]

        weight_union += abs( w1k - w2k ) + 1 #weights[k]
    #print weight_union
    for k in inters:
        weight_inters += abs( w1[k] - w2[k] ) + 1 #weights[k]
    #print weight_inters

    return float(weight_inters) / float(weight_union)

def readwifi(fn):

    wifisets = []
    wifiset = {}

    f = open(fn, 'r')    
    for line in f:
        #i += 1
        #if "{}" in line:
            #continue
        if line == "Record begins\n":
            continue
        try:
            data = str2data(line)
        except ValueError:
            print "INCOMPLETE DATA"
            #print line
            #break
        if 'wifi' in data:
            aps = data['wifi']
            t = 0
            if 't' in aps:
                t = aps['t']
                #print dm.time2hms(int(aps['t'])/1000) + ">>>>>>>>>>>>>>>>>>>>>>>>"
                del(aps['t'])
            else:
                print "No T ****************************************"
            for ap,value in aps.items():
                #if int(value[1])<-80:
                wifiset[ap] = int(value[1])
        wifis = wifiset.copy()
        wifisets.append(wifis)

    f.close()
    return wifisets


